import nodemailer from "nodemailer";
import { emailTemplates } from "./emailTemplates";

// 邮件服务类
export class EmailService {
  private transporter!: nodemailer.Transporter;
  private config: {
    mail: {
      host: string;
      port: string;
      secure: boolean;
      auth: {
        user: string;
        pass: string;
      };
    };
    public: {
      appName: string;
      appUrl: string;
    };
  };

  constructor() {
    this.config = useRuntimeConfig();
    this.initializeTransporter();
  }

  // 初始化邮件传输器
  private initializeTransporter() {
    // 验证配置
    if (!this.config.mail.auth.user || !this.config.mail.auth.pass) {
      console.error("邮件配置不完整：缺少用户名或密码");
      throw new Error("邮件配置不完整");
    }
    this.transporter = nodemailer.createTransport({
      host: this.config.mail.host,
      port: parseInt(this.config.mail.port),
      secure: this.config.mail.secure,
      auth: {
        user: this.config.mail.auth.user,
        pass: this.config.mail.auth.pass,
      },
      // 添加调试信息
      debug: process.env.NODE_ENV === "development",
      logger: process.env.NODE_ENV === "development",
      // 添加连接超时设置
      connectionTimeout: 60000,
      greetingTimeout: 30000,
      socketTimeout: 60000,
    });
  }

  // 验证邮件配置
  async verifyConnection(): Promise<boolean> {
    try {
      await this.transporter.verify();
      console.log("邮件服务连接成功");
      return true;
    } catch (error) {
      console.error("邮件服务连接失败:", error);
      return false;
    }
  }

  // 发送验证码邮件
  async sendVerificationCode(
    email: string,
    code: string
  ): Promise<{ success: boolean; error?: string }> {
    try {
      const template = emailTemplates.verificationCode(
        code,
        this.config.public.appName
      );

      const mailOptions = {
        from: this.config.mail.auth.user,
        to: email,
        subject: template.subject,
        html: template.html,
        text: template.text,
      };

      const result = await this.transporter.sendMail(mailOptions);
      console.log("验证码邮件发送成功:", result.messageId);
      return { success: true };
    } catch (error) {
      console.error("发送验证码邮件失败:", error);
      return {
        success: false,
        error: error instanceof Error ? error.message : "邮件发送失败",
      };
    }
  }

  // 发送注册成功邮件
  async sendRegistrationSuccess(
    email: string,
    username: string
  ): Promise<{ success: boolean; error?: string }> {
    try {
      const template = emailTemplates.registrationSuccess(
        username,
        this.config.public.appName
      );

      const mailOptions = {
        from: this.config.mail.auth.user,
        to: email,
        subject: template.subject,
        html: template.html,
        text: template.text,
      };

      const result = await this.transporter.sendMail(mailOptions);
      console.log("注册成功邮件发送成功:", result.messageId);

      return { success: true };
    } catch (error) {
      console.error("发送注册成功邮件失败:", error);
      return {
        success: false,
        error: error instanceof Error ? error.message : "邮件发送失败",
      };
    }
  }

  // 发送自定义邮件
  async sendCustomEmail(
    to: string,
    subject: string,
    html: string,
    text?: string
  ): Promise<{ success: boolean; error?: string }> {
    try {
      const mailOptions = {
        from: this.config.mail.auth.user,
        to,
        subject,
        html,
        text: text || html.replace(/<[^>]*>/g, ""), // 如果没有提供纯文本，从HTML中提取
      };

      const result = await this.transporter.sendMail(mailOptions);
      console.log("自定义邮件发送成功:", result.messageId);

      return { success: true };
    } catch (error) {
      console.error("发送自定义邮件失败:", error);
      return {
        success: false,
        error: error instanceof Error ? error.message : "邮件发送失败",
      };
    }
  }
}

// 创建单例实例
export const emailService = new EmailService();
